﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace MessageSystem.Default.infrastructure
{
    public unsafe class block
    {
        public byte[]   buffer;
        public byte*    Point;
        public block    next;
        public int      refcount;
        public IntPtr   Ptr;
        public GCHandle Handle;

        public block(int size)
        {
            buffer = new byte[size];
            next = null;
            refcount = 1;

            Handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            Ptr = Handle.AddrOfPinnedObject();
            Point = (byte*)Ptr.ToPointer();
        }

        public byte* offset(UInt32 index)
        {
            return (byte*)&Point[index];
        }

        public void free()
        {
            Handle.Free();
        }

        public block duplicate()
        {
            ++refcount;
            return this;
        }

        public bool release()
        {
            return --refcount == 0;
        }
    }
}
